// 搜索服务
// 处理视频搜索、用户搜索、分类搜索等功能

import { dataService } from './simpleDbService.js'

// 模拟API延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 搜索服务
export const searchService = {
  // 获取搜索建议
  getSearchSuggestions(keyword) {
    return new Promise((resolve) => {
      // 模拟延迟
      setTimeout(() => {
        // 生成基于关键词的真实搜索建议
        const suggestions = [];
        
        // 视频标题建议
        suggestions.push({
          type: 'video',
          title: keyword + ' 教程',
          relevance: 95
        });
        suggestions.push({
          type: 'video',
          title: keyword + ' 最新',
          relevance: 90
        });
        
        // 标签建议
        suggestions.push({
          type: 'tag',
          title: keyword,
          relevance: 98
        });
        
        // 根据相关性排序
        suggestions.sort((a, b) => b.relevance - a.relevance);
        
        resolve(suggestions);
      }, 100);
    });
  },
  
  // 搜索视频
  async searchVideos(keyword, filters = {}, page = 1, limit = 20) {
    try {
      await delay(300)
      
      // 从数据库获取所有视频
      let videos = dataService.videos.getAll()
      
      // 如果数据库为空，生成模拟数据
      if (videos.length === 0) {
        videos = this.generateMockVideos(100)
      }
      
      // 增强的关键词搜索算法 - 基于相关性评分
      if (keyword) {
        videos = videos.map(video => {
          let relevance = 0;
          const lowerKeyword = keyword.toLowerCase();
          
          // 标题匹配（权重最高）
          if (video.title.toLowerCase().includes(lowerKeyword)) {
            relevance += 100;
            // 完全匹配额外加分
            if (video.title.toLowerCase() === lowerKeyword) {
              relevance += 50;
            }
          }
          
          // 描述匹配（权重中等）
          if (video.description.toLowerCase().includes(lowerKeyword)) {
            relevance += 50;
          }
          
          // 标签匹配（权重较高）
          if (video.tags) {
            video.tags.forEach(tag => {
              if (tag.toLowerCase().includes(lowerKeyword)) {
                relevance += 80;
                // 标签完全匹配额外加分
                if (tag.toLowerCase() === lowerKeyword) {
                  relevance += 30;
                }
              }
            });
          }
          
          // 作者名匹配
          if (video.author && video.author.name && video.author.name.toLowerCase().includes(lowerKeyword)) {
            relevance += 60;
          }
          
          return { ...video, relevance };
        }).filter(video => video.relevance > 0)
          .sort((a, b) => b.relevance - a.relevance); // 按相关性排序
      }
      
      // 分类过滤
      if (filters.category && filters.category !== '全部') {
        videos = videos.filter(video => video.category === filters.category)
      }
      
      // 时间过滤
      if (filters.timeRange) {
        const now = new Date()
        let startTime
        
        switch (filters.timeRange) {
          case 'today':
            startTime = new Date(now.setDate(now.getDate() - 1))
            break
          case 'week':
            startTime = new Date(now.setDate(now.getDate() - 7))
            break
          case 'month':
            startTime = new Date(now.setMonth(now.getMonth() - 1))
            break
          case 'year':
            startTime = new Date(now.setFullYear(now.getFullYear() - 1))
            break
        }
        
        if (startTime) {
          videos = videos.filter(video => new Date(video.createdDate) >= startTime)
        }
      }
      
      // 排序 - 可以覆盖默认的相关性排序
      if (filters.sortBy) {
        switch (filters.sortBy) {
          case 'relevance':
            // 保持相关性排序
            break
          case 'views':
            videos.sort((a, b) => (b.views || 0) - (a.views || 0))
            break
          case 'newest':
            videos.sort((a, b) => new Date(b.createdDate) - new Date(a.createdDate))
            break
          case 'likes':
            videos.sort((a, b) => (b.likes || 0) - (a.likes || 0))
            break
          case 'highestRated':
            // 假设有评分字段的情况下
            videos.sort((a, b) => (b.rating || 0) - (a.rating || 0))
            break
        }
      }
      
      // 分页处理
      const start = (page - 1) * limit
      const end = start + limit
      
      return {
        videos: videos.slice(start, end),
        total: videos.length,
        page,
        limit,
        totalPages: Math.ceil(videos.length / limit),
        suggestions: this.generateSearchSuggestions(keyword),
        keyword
      }
    } catch (error) {
      console.error('搜索视频失败:', error)
      throw error
    }
  },
  
  // 搜索用户
  async searchUsers(keyword, page = 1, limit = 10) {
    try {
      await delay(300)
      
      // 从数据库获取所有用户
      let users = dataService.users.getAll()
      
      // 如果数据库为空，生成模拟数据
      if (users.length === 0) {
        users = this.generateMockUsers(50)
      }
      
      // 关键词搜索
      if (keyword) {
        const lowerKeyword = keyword.toLowerCase()
        users = users.filter(user => 
          user.username.toLowerCase().includes(lowerKeyword) ||
          (user.nickname && user.nickname.toLowerCase().includes(lowerKeyword))
        )
      }
      
      // 分页处理
      const start = (page - 1) * limit
      const end = start + limit
      
      return {
        users: users.slice(start, end),
        total: users.length,
        page,
        limit,
        totalPages: Math.ceil(users.length / limit)
      }
    } catch (error) {
      console.error('搜索用户失败:', error)
      throw error
    }
  },
  
  // 获取热门搜索
  async getHotSearches(limit = 20) {
    try {
      await delay(100)
      
      // 模拟热门搜索数据
      const hotSearches = [
        { keyword: '热门电影推荐', hot: true, icon: '🔥' },
        { keyword: '游戏攻略', hot: true },
        { keyword: '美食制作', trend: 'up' },
        { keyword: '科技新闻', trend: 'up' },
        { keyword: '学习教程', hot: true },
        { keyword: '旅行vlog', trend: 'down' },
        { keyword: '健身计划', trend: 'up' },
        { keyword: '生活小技巧', hot: false },
        { keyword: '音乐现场', hot: true },
        { keyword: '动漫更新', trend: 'up' },
        { keyword: '职场经验', hot: false },
        { keyword: '手工DIY', hot: false },
        { keyword: '宠物日常', trend: 'up' },
        { keyword: '摄影技巧', hot: false },
        { keyword: '育儿知识', hot: false },
        { keyword: '装修设计', trend: 'down' },
        { keyword: '投资理财', hot: false },
        { keyword: '英语口语', trend: 'up' },
        { keyword: '美妆教程', hot: true },
        { keyword: '搞笑视频', hot: true }
      ]
      
      return hotSearches.slice(0, limit)
    } catch (error) {
      console.error('获取热门搜索失败:', error)
      return []
    }
  },
  
  // 获取搜索建议
  async getSearchSuggestions(keyword, limit = 10) {
    try {
      await delay(100)
      
      if (!keyword) return []
      
      const suggestions = this.generateSearchSuggestions(keyword)
      return suggestions.slice(0, limit)
    } catch (error) {
      console.error('获取搜索建议失败:', error)
      return []
    }
  },
  
  // 记录搜索历史
  async recordSearchHistory(userId, keyword) {
    try {
      await delay(50)
      
      // 获取用户
      const user = dataService.users.getById(userId)
      if (!user) return
      
      // 获取历史记录
      let history = user.searchHistory || []
      
      // 移除重复项
      history = history.filter(item => item !== keyword)
      
      // 添加到开头
      history.unshift(keyword)
      
      // 限制数量
      if (history.length > 50) {
        history = history.slice(0, 50)
      }
      
      // 更新用户
      dataService.users.update(userId, { searchHistory: history })
    } catch (error) {
      console.error('记录搜索历史失败:', error)
    }
  },
  
  // 获取搜索历史
  async getSearchHistory(userId, limit = 20) {
    try {
      await delay(50)
      
      // 获取用户
      const user = dataService.users.getById(userId)
      if (!user || !user.searchHistory) {
        return []
      }
      
      return user.searchHistory.slice(0, limit)
    } catch (error) {
      console.error('获取搜索历史失败:', error)
      return []
    }
  },
  
  // 清除搜索历史
  async clearSearchHistory(userId) {
    try {
      await delay(50)
      
      // 获取用户
      const user = dataService.users.getById(userId)
      if (user) {
        dataService.users.update(userId, { searchHistory: [] })
      }
      
      return { success: true }
    } catch (error) {
      console.error('清除搜索历史失败:', error)
      throw error
    }
  },
  
  // 生成搜索建议
  generateSearchSuggestions(keyword) {
    if (!keyword) return []
    
    const baseSuggestions = [
      `${keyword}教程`,
      `${keyword}技巧`,
      `${keyword}最新`,
      `${keyword}推荐`,
      `${keyword}入门`,
      `${keyword}解析`,
      `${keyword}合集`,
      `${keyword}教学`,
      `${keyword}分享`,
      `${keyword}展示`
    ]
    
    return baseSuggestions
  },
  
  // 生成模拟视频数据
  generateMockVideos(count) {
    const categories = ['动漫', '游戏', '音乐', '科技', '生活', '教育', '娱乐', '美食', '旅行', '体育']
    const tags = ['热门', '推荐', '教程', '技巧', '最新', '精彩', '收藏', '分享', '点赞', '评论']
    
    return Array.from({ length: count }, (_, index) => {
      const videoTags = []
      const tagCount = Math.floor(Math.random() * 4) + 1
      
      for (let i = 0; i < tagCount; i++) {
        const tag = tags[Math.floor(Math.random() * tags.length)]
        if (!videoTags.includes(tag)) {
          videoTags.push(tag)
        }
      }
      
      return {
        id: `video_${index}`,
        title: `${this.getRandomTitle()} - 精彩内容${index + 1}`,
        description: `这是一个关于${this.getRandomTitle()}的精彩视频，包含了丰富的内容和实用的技巧。`,
        thumbnail: `https://placehold.co/400x225/00a1d6/FFFFFF?text=Video+${index + 1}`,
        duration: Math.floor(Math.random() * 600) + 30,
        views: Math.floor(Math.random() * 1000000),
        likes: Math.floor(Math.random() * 100000),
        comments: Math.floor(Math.random() * 10000),
        author: {
          id: `author_${Math.floor(Math.random() * 50)}`,
          name: `创作者${Math.floor(Math.random() * 50)}`,
          avatar: `https://placehold.co/50x50/667eea/FFFFFF?text=A`
        },
        category: categories[Math.floor(Math.random() * categories.length)],
        tags: videoTags,
        createdDate: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString()
      }
    })
  },
  
  // 生成模拟用户数据
  generateMockUsers(count) {
    return Array.from({ length: count }, (_, index) => ({
      id: `user_${index}`,
      username: `user${index}`,
      nickname: `用户${index}`,
      avatar: `https://placehold.co/50x50/667eea/FFFFFF?text=U${index}`,
      followers: Math.floor(Math.random() * 10000),
      uploads: Math.floor(Math.random() * 100)
    }))
  },
  
  // 获取随机标题
  getRandomTitle() {
    const titles = [
      '精彩瞬间集锦',
      '新手入门教程',
      '深度解析',
      '趣味挑战',
      '生活小技巧',
      '知识科普',
      '美食制作',
      '旅行vlog',
      '游戏攻略',
      '音乐欣赏',
      '健身指导',
      '职场经验',
      '历史揭秘',
      '科技前沿',
      '创意手工'
    ]
    return titles[Math.floor(Math.random() * titles.length)]
  }
}

// 导出默认服务
export default searchService